import { createSlice } from "@reduxjs/toolkit";

const cartSlice = createSlice({
  name: "cart",
  initialState: {
    // 转化json(先获取本地存储)|| []
    cartList: JSON.parse(localStorage.getItem("cartList")) || [],
  },
  reducers: {
    // 添加购物车
    addCart(state, action) {
      const payload = action.payload;
      //  先判断购物车是存在该项数据
      const item = state.cartList.find((v) => v.id === payload.id);
      // 存在数量++
      if (item) item.count++;
      // 不存在 推入新数据
      else {
        state.cartList.push({
          ...payload,
          count: 1,
          state: false,
        });
      }
      // 每次dispatch action 之后。 也就是数据改变之后， 重新存储cartList即可
      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    },
    // 减少购物车
    subCart(state, action) {
      const payload = action.payload;
      //  先判断购物车是存在该项数据
      const item = state.cartList.find((v) => v.id === payload.id);
      // 存在数量++
      if (item) item.count--;

      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    },

    // 切换状态
    changeState(state, action) {
      const payload = action.payload;
      // 找到是存在该项数据
      const item = state.cartList.find((v) => v.id === payload.id);
      // 修改 状态 核心就是自身取反
      if (item) item.state = !item.state

      localStorage.setItem('cartList', JSON.stringify(state.cartList))
    },
    // 切换所有状态
    changeAllState(state, action) {
      state.cartList.forEach(v => {
        v.state = action.payload
      })
    }
  },
});

export default cartSlice;
export const { addCart, subCart, changeState, changeAllState } = cartSlice.actions;
